<template>
  <div class="chronic-disease-container">
    <div class="header">
      <h3>慢病管理</h3>
    </div>

    <!-- 我的慢病诊断列表 -->
    <div class="section-card">
      <h4>我的慢病诊断</h4>
      <p v-if="chronicDiseases.length === 0">暂无诊断信息，请添加或前往问诊/健康检测获取。</p>
      <div v-else class="disease-list">
        <el-card v-for="disease in chronicDiseases" :key="disease.id" shadow="hover" class="disease-item-card">
          <template #header>
            <div class="card-header">
              <span>{{ disease.name }}</span>
              <el-tag size="small">{{ disease.diagnosisDate }} 诊断</el-tag>
            </div>
          </template>
          <div class="card-content">
            <p><strong>主要症状:</strong> {{ disease.mainSymptoms || '无' }}</p>
            <p><strong>治疗方案:</strong> {{ disease.treatmentPlan || '无' }}</p>
            <p><strong>用药情况:</strong>
              <span v-if="disease.medications && disease.medications.length">
                {{ disease.medications.join('、') }}
              </span>
              <span v-else>无</span>
            </p>
            <p><strong>最近复查:</strong> {{ disease.lastCheckupDate || '无' }}</p>
            <p><strong>下次复诊:</strong> {{ disease.nextFollowUpDate || '无' }}</p>
          </div>
          <div class="card-actions">
            <el-button type="text" size="small" @click="editDisease(disease)">编辑</el-button>
            <el-button type="text" size="small" @click="deleteDisease(disease.id)" class="delete-btn">删除</el-button>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 添加/编辑慢病记录表单 -->
    <div class="section-card">
      <h4>{{ editingDiseaseId ? '编辑慢病记录' : '添加新慢病记录' }}</h4>
      <el-form :model="currentEditingDisease" label-position="top">
        <el-form-item label="慢病名称">
          <el-input v-model="currentEditingDisease.name" placeholder="例如：高血压、糖尿病、冠心病等" />
        </el-form-item>
        <el-form-item label="诊断日期">
          <el-date-picker v-model="currentEditingDisease.diagnosisDate" type="date" placeholder="选择诊断日期"
            style="width: 100%;" />
        </el-form-item>
        <el-form-item label="主要症状">
          <el-input v-model="currentEditingDisease.mainSymptoms" type="textarea" :rows="2"
            placeholder="请输入主要症状，如头晕、乏力、口渴等" />
        </el-form-item>
        <el-form-item label="治疗方案">
          <el-input v-model="currentEditingDisease.treatmentPlan" type="textarea" :rows="2"
            placeholder="请输入治疗方案，包括药物、饮食、运动等" />
        </el-form-item>
        <el-form-item label="用药情况 (多个请用逗号分隔)">
          <el-input v-model="currentEditingDisease.medicationsString" placeholder="例如：苯磺酸氨氯地平片,二甲双胍,阿司匹林等" />
        </el-form-item>
        <el-form-item label="最近复查日期">
          <el-date-picker v-model="currentEditingDisease.lastCheckupDate" type="date" placeholder="选择最近复查日期"
            style="width: 100%;" />
        </el-form-item>
        <el-form-item label="下次复诊日期">
          <el-date-picker v-model="currentEditingDisease.nextFollowUpDate" type="date" placeholder="选择下次复诊日期"
            style="width: 100%;" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="saveDisease">
            {{ editingDiseaseId ? '更新记录' : '添加记录' }}
          </el-button>
          <el-button v-if="editingDiseaseId" @click="cancelEdit">取消</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 查看历史管理方案卡片 -->
    <el-card shadow="hover" class="history-card" @click="goToHistory">
      <div class="history-card-content">
        <el-icon class="history-icon">
          <Clock />
        </el-icon>
        <span>查看历史慢病记录</span>
        <el-icon class="arrow-icon">
          <ArrowRight />
        </el-icon>
      </div>
    </el-card>

  </div>
</template>

<script setup>
import { ArrowRight, Clock } from '@element-plus/icons-vue'; // 导入新图标
import { ElMessage, ElMessageBox } from 'element-plus'; // 导入 ElMessageBox
import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

// 假设的API函数，待实际对接后端
// import { getChronicInfoApi, addOrUpdateChronicPlanApi } from '../api/chronic' 

const router = useRouter()

// 模拟慢病数据
const chronicDiseases = ref([
  {
    id: 1,
    name: '高血压',
    diagnosisDate: '2023-01-15',
    mainSymptoms: '头晕，颈部僵硬',
    treatmentPlan: '控制饮食，规律运动，按时服用降压药',
    medications: ['苯磺酸氨氯地平片', '氢氯噻嗪片'],
    lastCheckupDate: '2024-03-01',
    nextFollowUpDate: '2024-06-01',
  },
  {
    id: 2,
    name: '糖尿病',
    diagnosisDate: '2022-11-20',
    mainSymptoms: '多饮，多尿，体重减轻',
    treatmentPlan: '饮食控制，适量运动，胰岛素注射',
    medications: ['二甲双胍', '胰岛素'],
    lastCheckupDate: '2024-02-10',
    nextFollowUpDate: '2024-05-10',
  },
])

const newDiseaseDefault = {
  id: null,
  name: '',
  diagnosisDate: null,
  mainSymptoms: '',
  treatmentPlan: '',
  medicationsString: '',
  lastCheckupDate: null,
  nextFollowUpDate: null,
}

const currentEditingDisease = reactive({ ...newDiseaseDefault })
const loading = ref(false)
const editingDiseaseId = ref(null) // 用于标记是否在编辑现有方案

// 保存慢病记录（添加或更新）
const saveDisease = async () => {
  if (!currentEditingDisease.name || !currentEditingDisease.diagnosisDate) {
    ElMessage.warning('请填写慢病名称和诊断日期')
    return
  }

  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    const medicationsArray = currentEditingDisease.medicationsString
      .split(/[,，]/)
      .map(item => item.trim())
      .filter(item => item !== '')

    if (editingDiseaseId.value) {
      // 更新现有记录
      const index = chronicDiseases.value.findIndex(d => d.id === editingDiseaseId.value)
      if (index !== -1) {
        chronicDiseases.value[index] = {
          ...currentEditingDisease,
          medications: medicationsArray,
          diagnosisDate: currentEditingDisease.diagnosisDate ? currentEditingDisease.diagnosisDate.toISOString().split('T')[0] : null,
          lastCheckupDate: currentEditingDisease.lastCheckupDate ? currentEditingDisease.lastCheckupDate.toISOString().split('T')[0] : null,
          nextFollowUpDate: currentEditingDisease.nextFollowUpDate ? currentEditingDisease.nextFollowUpDate.toISOString().split('T')[0] : null,
        }
        ElMessage.success('慢病记录更新成功')
      }
    } else {
      // 添加新记录
      const newId = Math.max(...chronicDiseases.value.map(d => d.id), 0) + 1
      chronicDiseases.value.push({
        ...currentEditingDisease,
        id: newId,
        medications: medicationsArray,
        diagnosisDate: currentEditingDisease.diagnosisDate ? currentEditingDisease.diagnosisDate.toISOString().split('T')[0] : null,
        lastCheckupDate: currentEditingDisease.lastCheckupDate ? currentEditingDisease.lastCheckupDate.toISOString().split('T')[0] : null,
        nextFollowUpDate: currentEditingDisease.nextFollowUpDate ? currentEditingDisease.nextFollowUpDate.toISOString().split('T')[0] : null,
      })
      ElMessage.success('慢病记录添加成功')
    }
    resetForm()
  } catch (error) {
    console.error('保存慢病记录失败:', error)
    ElMessage.error('保存慢病记录失败，请重试')
  } finally {
    loading.value = false
  }
}

// 编辑慢病记录
const editDisease = (disease) => {
  Object.assign(currentEditingDisease, {
    ...disease,
    medicationsString: disease.medications ? disease.medications.join(', ') : '',
    diagnosisDate: disease.diagnosisDate ? new Date(disease.diagnosisDate) : null,
    lastCheckupDate: disease.lastCheckupDate ? new Date(disease.lastCheckupDate) : null,
    nextFollowUpDate: disease.nextFollowUpDate ? new Date(disease.nextFollowUpDate) : null,
  })
  editingDiseaseId.value = disease.id
}

// 取消编辑
const cancelEdit = () => {
  resetForm()
}

// 删除慢病记录
const deleteDisease = async (id) => {
  ElMessageBox.confirm('确定要删除这条慢病记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 300))
      chronicDiseases.value = chronicDiseases.value.filter(d => d.id !== id)
      ElMessage.success('慢病记录删除成功')
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 重置表单
const resetForm = () => {
  Object.assign(currentEditingDisease, newDiseaseDefault)
  editingDiseaseId.value = null
}

const goToHistory = () => {
  router.push('/chronic/history')
}

onMounted(() => {
  // 模拟从后端获取初始数据
  // fetchChronicInfo()
})
</script>

<style scoped>
.chronic-disease-container {
  padding: 15px;
  /* 调整内边距 */
  background-color: #f7f8fa;
}

.header {
  text-align: left;
  /* 标题左对齐 */
  margin-bottom: 25px;
}

.header h3 {
  font-size: 24px;
  color: #333;
}

.section-card {
  background-color: #fff;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.section-card h4 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #2e8b57;
  font-size: 20px;
}

.disease-list .disease-item-card {
  margin-bottom: 15px;
  border-left: 5px solid #2e8b57;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  border-radius: 12px;
  /* 确保卡片圆角 */
}

.disease-list .disease-item-card:last-child {
  margin-bottom: 0;
}

.disease-item-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 17px;
  /* 调整字体大小 */
  font-weight: bold;
  color: #333;
  padding-bottom: 10px;
  /* 增加底部填充 */
  border-bottom: 1px solid #eee;
  /* 添加底部边框 */
  margin-bottom: 10px;
  /* 增加底部外边距 */
}

.disease-item-card .card-content p {
  font-size: 14px;
  line-height: 1.6;
  color: #555;
  margin-bottom: 8px;
}

.disease-item-card .card-content p:last-child {
  margin-bottom: 0;
}

.disease-item-card .card-actions {
  text-align: right;
  margin-top: 15px;
  /* 增加上边距 */
}

.disease-item-card .card-actions .el-button {
  margin-left: 10px;
  border-radius: 8px;
  /* 统一按钮圆角 */
  height: 36px;
  /* 调整按钮高度 */
}

.disease-item-card .card-actions .delete-btn {
  color: #f56c6c;
}

.el-form-item__label {
  font-size: 15px;
  color: #333;
  margin-bottom: 5px !important;
}

.section-card .el-button--primary {
  width: 100%;
  background-color: #2e8b57;
  border-color: #2e8b57;
  border-radius: 10px;
  height: 45px;
  font-size: 16px;
  margin-top: 15px;
}

.section-card .el-button {
  border-radius: 10px;
  height: 45px;
  font-size: 16px;
  margin-top: 15px;
}

.history-card {
  background-color: #fff;
  padding: 15px;
  border-radius: 12px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
  cursor: pointer;
}

.history-card-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 16px;
  color: #2e8b57;
  font-weight: 500;
}

.history-icon {
  font-size: 24px;
  margin-right: 10px;
}

.arrow-icon {
  font-size: 20px;
  color: #999;
}

/* 调整输入框和日期选择器圆角 */
:deep(.el-input__wrapper),
:deep(.el-textarea__inner),
:deep(.el-date-editor.el-input__wrapper) {
  border-radius: 10px !important;
  box-shadow: 0 0 0 1px #dcdfe6 inset !important;
}

:deep(.el-input__wrapper.is-focus),
:deep(.el-textarea__inner:focus),
:deep(.el-date-editor.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #2e8b57 inset !important;
}

:deep(.el-input-number__increase, .el-input-number__decrease) {
  border-radius: 0 10px 10px 0 !important;
}
</style>